﻿using GylCSharpUtils.P2PIPC.Utils;
using System;
using static GylCSharpUtils.P2PIPC.Utils.NoBufferShareMemory;

namespace GylCSharpUtils.P2PIPC.Client {
    public class NoBufferClient : AIPCClient {

        protected NoBufferShareMemory sm { get; private set; }
        public string RealPath { get; private set; }
        public NoBufferClient(string path, bool isA, int maxMsgSize = 4 << 20, int timeout_ms = 10 * 1000 ) {
            sm = new NoBufferShareMemory(path, maxMsgSize, isA, timeout_ms);
            RealPath = sm.RealPath;
        }

        public override bool CanReceive() {
            CheckSerializer();
            return sm.CanRead();
        }

        public override bool CanSend() {
            CheckSerializer();
            return sm.CanWrite();
        }

        public override T Receive<T>() {
            CheckSerializer();
            byte[] data = sm.ReadData();
            if(data == null) return default(T);
            return Serializer.Deseriallize<T>(data);
        }

        public override bool Send(object msg) {
            CheckSerializer();
            return sm.WriteData(Serializer.Serialize(msg));
        }


        private bool CheckSerializer() {
            if(Serializer == null) {
                throw new Exception("未配置序列化器");
            }
            return true;
        }


        public BaseInfo GetBaseInfo() {
            sm.ReadBaseInfo(out BaseInfo info);
            return info;
        }

        public override bool Alive() {
            return sm.UserAlive();
        }
    }
}
